package com.shengqin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shengqin.common.pojo.CommonPage;
import com.shengqin.config.CommonException;
import com.shengqin.entity.ScoreTemplate;
import com.shengqin.mapper.ScoreTemplateMapper;
import com.shengqin.pojo.plan.ScoreTemplateParam;
import com.shengqin.service.IScoreTemplateService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ScoreTemplateServiceImpl extends ServiceImpl<ScoreTemplateMapper, ScoreTemplate> implements IScoreTemplateService {


    @Override
    public Page<ScoreTemplate> queryPage(CommonPage<ScoreTemplateParam> scoreTemplateParam) {
        ScoreTemplateParam param = scoreTemplateParam.getQueryParam();
        QueryWrapper<ScoreTemplate> wrapper = new QueryWrapper<>();
        if (StringUtils.hasLength(param.getName())) {
            wrapper.lambda().like(ScoreTemplate::getName, param.getName());
        }
        if (param.getType() != null) {
            wrapper.lambda().eq(ScoreTemplate::getType, param.getType());
        }
        wrapper.lambda().and(w -> w.eq(ScoreTemplate::getType, 1).or().eq(ScoreTemplate::getCreateUserId, StpUtil.getLoginId().toString()));
        wrapper.lambda().orderByDesc(ScoreTemplate::getId);
        Page<ScoreTemplate> templatePage = new Page<>(scoreTemplateParam.getPageNo(), scoreTemplateParam.getPageSize());
        page(templatePage, wrapper);
        return templatePage;
    }

    @Override
    public Boolean onSave(ScoreTemplate scoreTemplate) {
        if (scoreTemplate.getId() == null) {
            scoreTemplate.setCreateTime(LocalDateTime.now());
            scoreTemplate.setCreateUserId(Integer.valueOf(StpUtil.getLoginId().toString()));
        }
        ScoreTemplate oldScoreTemplate = getById(scoreTemplate.getId());
        if (oldScoreTemplate != null) {
            if (!oldScoreTemplate.getCreateUserId().equals(Integer.valueOf(StpUtil.getLoginId().toString()))) {
                throw new CommonException("您没有权限编辑该评分模板");
            }
        }
        return saveOrUpdate(scoreTemplate);
    }

    @Override
    public List<ScoreTemplate> queryList(ScoreTemplateParam scoreTemplateParam) {
        QueryWrapper<ScoreTemplate> wrapper = new QueryWrapper<>();
        wrapper.lambda().and(w -> w.eq(ScoreTemplate::getType, 1).or().eq(ScoreTemplate::getCreateUserId, StpUtil.getLoginId().toString()));
        wrapper.lambda().orderByDesc(ScoreTemplate::getId);
        return list(wrapper);
    }
}
